package com.example.mymusicplayer;

import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.transition.Hold;

import java.util.ArrayList;

public class AlbumAdapterDetail extends RecyclerView.Adapter<AlbumAdapterDetail.ViewHolder> {
    private Context mContext;
    private ArrayList<MusicFiles> mFiles;
    View view;

    public AlbumAdapterDetail(Context mContext, ArrayList<MusicFiles> mFiles) {
        this.mContext = mContext;
        this.mFiles = mFiles;
    }


    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        view = LayoutInflater.from(mContext).inflate(R.layout.music_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.TheAlbumName.setText(mFiles.get(position).getTitle());
        byte[] image = getAlbumAct(mFiles.get(position).getPath());
        if (image != null) {
            Glide.with(mContext).asBitmap().load(image).into(holder.AlbumView);
        } else {
            Glide.with(mContext).load(R.drawable.ic_baseline_hourglass_empty_24).into(holder.AlbumView);
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext,Media_page.class);
                intent.putExtra("TheMsg","FromAlbum");
                intent.putExtra("position",position);
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mFiles.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        ImageView AlbumView;
        TextView TheAlbumName;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            AlbumView = itemView.findViewById(R.id.TheMusicAlbum);
            TheAlbumName=itemView.findViewById(R.id.MusicName);
        }
    }
    private byte[] getAlbumAct(String uri){
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try{
            retriever.setDataSource(uri);
        }
        catch(java.lang.RuntimeException e){
            return null;
        }
        byte[] art = retriever.getEmbeddedPicture();
        retriever.release();
        return art;
    }
}